package com.example.demo.aspect;

import com.example.demo.annotation.Distinct;
import com.example.demo.dao.DakaCountDao;
import com.example.demo.entity.DakaCount;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStreamWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class DistinctInterceptor implements HandlerInterceptor {
    private Map<String,String> variables= new HashMap<>();


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{
        //1.判断是否存在注解
        if(!(handler instanceof HandlerMethod)){
            System.out.println("不是HandlerMethod类型，则无需检查");
            return true;
        }
        HandlerMethod method = (HandlerMethod)handler;
        boolean flag=method.getMethod().isAnnotationPresent(Distinct.class);
        if(!flag){
            //不存在Distinct注解，则直接通过
            System.out.println("不存在Distinct注解，则直接通过");
            return true;
        }

        //判断map中是否有正在处理的mac
        String mac = request.getParameter("mac");
        if(mac!=null && !"".equals(mac)){
            String flag2 = variables.get(mac);
            if("true".equals(flag2)){
                response.sendError( HttpServletResponse.SC_FORBIDDEN,"该用户的上次请求还未处理完成");

//                ServletOutputStream outputStream = response.getOutputStream();
//                outputStream.println("no repat!!!");
//                OutputStreamWriter ow=new OutputStreamWriter(outputStream,"GB2312");
//                ow.write("请勿重复点击");
//                ow.flush();
//                ow.close();
                return false;
            }
            variables.put(mac,"true");
        }
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {

        //判断map中是否有正在处理的mac
        String mac = request.getParameter("mac");
        if(mac!=null && !"".equals(mac)){
            String s = variables.get(mac);
            if("true".equals(s)){
                variables.put(mac,"false");
            }
        }
    }
}
